#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
double dp[37][57];
double tP[57][57];
double P[57][57];
int Num[57];
int T,n,m,KK;
int main() {
	cin>>T;
	while (T--) {
		cin>>n>>m;
		for (int i=1; i<=n; ++i) {
			for (int j=1; j<=n; ++j) {
				cin>>tP[i][j];
			}
		}
		cin>>KK;
		for (int i=1; i<=n; ++i) cin>>Num[i];
		memset(P, 0, sizeof(P));
		for (int i=1; i<=n; ++i) {
			for (int j=1; j<=n; ++j) {
				P[Num[i]][Num[j]]+=tP[i][j];
			}
		}
		for (int i=0; i<KK; ++i) {
			for (int j=0; j<KK; ++j) cout<<P[i][j]<<" ";
			cout<<endl;
		}
		memset(dp, 0, sizeof(dp));
		for (int i=0; i<KK; ++i) dp[1][i]=1;
		for (int i=2; i<=m; ++i) {
			for (int j=0; j<KK; ++j) {
				double tmp=0;
				for (int k=0; k<KK; ++k) {
					if (abs(j-k)<=2) {
						tmp+=P[j][k]*dp[i-1][k];
						cout<<"tmp: "<<tmp<<endl;
					}
				}
				dp[i][j]=tmp;
			}
		}
		double res=dp[m][0];
		cout<<"res: "<<res<<endl;
		double tmp=0;
		for (int i=1; i<=n; ++i) {
			tmp+=dp[m-1][i];
		}
		cout<<endl;
		res=res*res-tmp;
		cout<<res<<endl;
	}
	return 0;
}
